#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import re
import base64

def getMusicId(url):
  '''获取音乐列表'''
  response = urllib2.urlopen(url)
  html = response.read()
  ids = re.findall(r'http%3A%2F%2Fg.top100.cn%2F12174704%2Fhtml%2Fdownload.html%3Fid%3D(.+?)\\x26resnum',html)
  if ids:
    return ids[0]
  else:
    return None

def get_music_download_url(musicId):
  '''get music download url'''
  if musicId == None:
    return None
  targetUrl = 'http://www.google.cn/music/top100/musicdownload?id=%s'%musicId
  html = urllib2.urlopen(targetUrl).read().replace('\n','')
  songUrlM = re.findall(r'<a href="/music/top100/url\?q=(.+?)&amp;ct=rdl.+?',html)
  if songUrlM:
    return urllib2.unquote(unicode(songUrlM[0],'utf-8'))
  else:
    return None

# mp3info: [title, album, artist]
def fetch_download_url_from_mp3info(mp3info):
  goole_music_search_url_prefix = 'http://www.google.cn/music/search?q='
  [title, album, artist] = mp3info
  if artist:
    _search_content = title+"+"+artist
  else:
    _search_content = title+"+"+album

  search_content = "+".join(_search_content.split(" "))
  url = goole_music_search_url_prefix + search_content
  print ">>> Google music search URL:", url
  musicid = getMusicId(url)
  return get_music_download_url(musicid)
